package com.yuyou.fn.controller;

import com.github.wens.mybatisplus.plugins.Page;
import com.google.common.collect.Maps;
import com.yuyou.fn.arrangement.service.IArrangementService;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.educational.entity.CourseClass;
import com.yuyou.fn.educational.entity.Period;
import com.yuyou.fn.educational.entity.PeriodSegment;
import com.yuyou.fn.educational.entity.Teacher;
import com.yuyou.fn.educational.service.ICourseClassService;
import com.yuyou.fn.educational.service.IPeriodSegmentService;
import com.yuyou.fn.educational.service.IPeriodService;
import com.yuyou.fn.educational.service.ITeacherService;
import com.yuyou.fn.educational.vo.CourseClassQueryVo;
import com.yuyou.fn.educational.vo.TeacherScheduleVo;
import com.yuyou.fn.platform.entity.SysUser;
import com.yuyou.fn.platform.permission.DataPermission;
import com.yuyou.fn.util.Webs;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by wens on 2017/7/12.
 */
@Controller
@RequestMapping("/api/admin/schedule")
public class AdminScheduleApiController extends ApiBaseController {

    @Resource
    private ICourseClassService courseClassService ;

    @Resource
    private IPeriodService periodService ;

    @Resource
    private IPeriodSegmentService periodSegmentService ;

    @Resource
    private ITeacherService teacherService ;

    @Resource
    private IArrangementService arrangementService;

    private static String[] weekNameArray = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};

    @ApiOperation("老师课表数据")
    @RequestMapping(value = "/scheduleDataOfTeacher", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Map<String,Object>> scheduleDataOfTeacher(CourseClassQueryVo courseClassQueryVo, HttpServletRequest request) {
        DataPermission dataPermission = getDataPermission(request);
        courseClassQueryVo.setIsArrangeTime(1);
        Page<CourseClass> page = courseClassService.findCourseClassByQueryForPage(courseClassQueryVo ,dataPermission , 1, 10000 );
        List<CourseClass> courseClassList = page.getRecords();
        List<CourseClass> newCourseClassList = new ArrayList<>(courseClassList.size());
        List<Long> teacherIds = new ArrayList<>();
        for(CourseClass courseClass : courseClassList ){

            if(courseClass.getStatus() == 2 ){//作废
                continue;
            }
            newCourseClassList.add(courseClass);
            if(courseClass.getTeacherId() != null ){
                teacherIds.add(courseClass.getTeacherId());
            }
        }
        teacherIds= Utils.removeDuplicate(teacherIds);
        List<Teacher> teacherList = teacherService.findByIds(teacherIds ,"teacherId" ,"teacherName" , "jobNature","teachSubjectIds","teachSubjectNames");

        Map<String,Object> data = Maps.newHashMap();
        data.put("teacherList" , teacherList );
        data.put("courseClassList" , newCourseClassList );
        return ReturnResult.success(data);
    }


    @ApiOperation("导出老师课表数据")
    @RequestMapping(value = "/exportScheduleDataOfTeacher", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Map<String,Object>> exportScheduleDataOfTeacher(@ModelAttribute CourseClassQueryVo courseClassQueryVo, HttpServletRequest request, HttpServletResponse response) throws Exception{
        if (courseClassQueryVo.getPeriodId()==null){
            throw new BusException("期数必选");
        }

        Period period=periodService.findById(courseClassQueryVo.getPeriodId());

        /*获取关联查询的期数*/
        Integer relativePeriodNo=null;
        if (period.getPeriodName().contains("寒") || period.getPeriodName().contains("暑")){
            relativePeriodNo=period.getPeriodNo()+1;
        }else if (period.getPeriodName().contains("春") || period.getPeriodName().contains("秋")){
            relativePeriodNo=period.getPeriodNo()-1;
        }
        Period relativePeriod=periodService.findByAreaPeriodNo(period.getAreaTeamId(),relativePeriodNo);

        /*没分段显示周几*/
        /* key periodId , value: 导出星期几， 1导出段次*/
        Map<Long,Integer> periodSegmentOrWeek=new HashMap<>();

        List<PeriodSegment> periodSegmentList=periodSegmentService.findByPeriodSegmentListByPeriodIds(Arrays.asList(period.getPeriodId(),relativePeriod.getPeriodId()));
        Map<Long, List<PeriodSegment>> periodSegmentMap = BeanUtils.toGroup(periodSegmentList, "periodId");
        if (periodSegmentMap.get(period.getPeriodId())!=null){
            if (periodSegmentMap.get(period.getPeriodId()).size()>1){
                periodSegmentOrWeek.put(period.getPeriodId(),1);
            }else{
                periodSegmentOrWeek.put(period.getPeriodId(),0);
            }
        }
        if (periodSegmentMap.get(relativePeriod.getPeriodId())!=null){
            if (periodSegmentMap.get(relativePeriod.getPeriodId()).size()>1){
                periodSegmentOrWeek.put(relativePeriod.getPeriodId(),1);
            }else{
                periodSegmentOrWeek.put(relativePeriod.getPeriodId(),0);
            }
        }

        courseClassQueryVo.setPeriodId(null);
        courseClassQueryVo.setPeriodIds(Arrays.asList(period.getPeriodId(),relativePeriod.getPeriodId()));


        DataPermission dataPermission = getDataPermission(request);
        courseClassQueryVo.setIsArrangeTime(1);
        Page<CourseClass> page = courseClassService.findCourseClassByQueryForPage(courseClassQueryVo ,dataPermission , 1, 10000 );
        List<CourseClass> courseClassList = page.getRecords();
        List<CourseClass> newCourseClassList = new ArrayList<>(courseClassList.size());
        List<Long> teacherIds = new ArrayList<>();
        /* 段次 key， 开课日位置*/
        Map<String,Integer> startClassDateMap=new TreeMap<>();

        /* 星期几 key， 星期几位置*/
        Map<String,Integer> weekMap=new TreeMap<>();


        for(CourseClass courseClass : courseClassList ){
            if(courseClass.getStatus() == 2 ){//作废
                continue;
            }
            Long  periodId=courseClass.getPeriodId();

            newCourseClassList.add(courseClass);
            if(courseClass.getTeacherId() != null ){
                teacherIds.add(courseClass.getTeacherId());
            }
            if (periodSegmentOrWeek.get(periodId)!=null && periodSegmentOrWeek.get(periodId)==0){
                weekMap.put(weekNameArray[TimeUtils.getWeekOfDate(courseClass.getStartCourseTime())],0);
            }else if (periodSegmentOrWeek.get(periodId)!=null && periodSegmentOrWeek.get(periodId)==1){
                String startClassDate=courseClass.getStartCourseTime()==null?"-":Utils.formatDate(courseClass.getStartCourseTime(),"yyyy-MM-dd");
                startClassDateMap.put(startClassDate,0);
            }
        }
        teacherIds= Utils.removeDuplicate(teacherIds);

        Iterator<String> starClasDateIterator = startClassDateMap.keySet().iterator();
        Integer offset=0;
        while(starClasDateIterator.hasNext()) {
            String key=starClasDateIterator.next();
            startClassDateMap.put(key,++offset);
        }

        Iterator<String> weekIterator = weekMap.keySet().iterator();
        while(weekIterator.hasNext()) {
            String key=weekIterator.next();
            weekMap.put(key,++offset);
        }






        List<Teacher> teacherList = teacherService.findByIds(teacherIds ,"teacherId" ,"teacherName" , "jobNature","teachSubjectIds","teachSubjectNames");



        Map<String,Object> data = Maps.newHashMap();
        data.put("teacherList" , teacherList );
        data.put("courseClassList" , newCourseClassList );

        /*key :teacherId+"_"+subjectId+"_"+studyingTime*/
        Map<String,List<CourseClass>> courseClassMap=new TreeMap<>();
        for (CourseClass courseClass:newCourseClassList){
            String key=(courseClass.getTeacherId()==null?("0"+courseClass.getStudyingTime()+courseClass.getClassId()):courseClass.getTeacherId()+"")+"_"+courseClass.getSubjectId()+"_"+courseClass.getStudyingTime();
            List<CourseClass> tempCourseClasses=courseClassMap.get(key);
            if (tempCourseClasses==null){
                tempCourseClasses=new ArrayList<>();
                courseClassMap.put(key,tempCourseClasses);
            }
            tempCourseClasses.add(courseClass);
        }
        List<TeacherScheduleVo> teacherScheduleVoList=new ArrayList<>(courseClassMap.size());
        for (Map.Entry<String,List<CourseClass>> entry:courseClassMap.entrySet()){
            List<CourseClass> courseClasses=entry.getValue();
            TeacherScheduleVo teacherScheduleVo=new TeacherScheduleVo();
            CourseClass one=courseClasses.get(0);
            teacherScheduleVo.setTeacherId(one.getTeacherId()==null?-1l:one.getTeacherId());
            teacherScheduleVo.setTeacherName(StringUtils.defaultString(one.getTeacherName()));
            teacherScheduleVo.setJobNature(one.getJobNature());
            teacherScheduleVo.setSubjectId(one.getSubjectId());
            teacherScheduleVo.setSubjectName(one.getSubjectName());
            teacherScheduleVo.setTime(one.getStudyingTime());
            teacherScheduleVo.setList(courseClasses);
            teacherScheduleVoList.add(teacherScheduleVo);
        }
        Webs.writeExcel(request,response, courseClassService.exportScheduleDataOfTeacher(teacherScheduleVoList,startClassDateMap,weekMap,periodSegmentOrWeek), "老师课表");
        return ReturnResult.success(data);
    }


    @ApiOperation("保存变更")
    @RequestMapping(value = "/saveChange", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveChange(@RequestParam("classId") Long classId ,@RequestParam(value = "className",required = false) String className ,@RequestParam(value = "studyingTime",required = false) String studyingTime ,@RequestParam(value = "teacherId" , required = false ) Long teacherId , HttpServletRequest request) {
        //courseClassService.saveClassChange(classId,className,studyingTime,teacherId);
        SysUser sysUser=this.getUser(request);
        arrangementService.saveClassChange(classId,className,studyingTime,teacherId,sysUser);
        return ReturnResult.success("OK");
    }



    @ApiOperation("校区课表数据")
    @RequestMapping(value = "/scheduleDataOfCampus", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Map<String,Object>> scheduleDataOfCampus(CourseClassQueryVo courseClassQueryVo, HttpServletRequest request) {
        DataPermission dataPermission = getDataPermission(request);
        courseClassQueryVo.setIsArrangeTime(1);
        Page<CourseClass> page = courseClassService.findCourseClassByQueryForPage(courseClassQueryVo ,dataPermission , 1, 10000 );
        List<CourseClass> courseClassList = page.getRecords();
        List<CourseClass> newCourseClassList = new ArrayList<>(courseClassList.size());
        for(CourseClass courseClass : courseClassList ){

            if(courseClass.getStatus() == 0 || courseClass.getStatus() == 2 ){//未开班 作废
                continue;
            }
            newCourseClassList.add(courseClass);

        }

        Map<String,Object> data = Maps.newHashMap();
        data.put("segmentList" , periodSegmentService.findPeriodSegmentList(courseClassQueryVo.getPeriodId()) );
        data.put("courseClassList" , newCourseClassList );
        return ReturnResult.success(data);
    }

}
